<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>平台每日指标</title>
    <#include "/header.html">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <script src="${request.contextPath}/statics/plugins/layui/layui.all.js"></script>
    <link rel="stylesheet" href="${request.contextPath}/statics/css/chartStyle.css">
    <script src="${request.contextPath}/statics/js/echarts.min.js"></script>
    <script src="${request.contextPath}/statics/js/transData.js"></script>
</head>
<style>
    .bootstrap-select{
        width: 100% !important;
    }
    .glyphicon-arrow-up{
        padding-left: 10px;
        color: red;
    }

    .glyphicon-arrow-down{
        padding-left: 10px;
        color: #76d471;
    }
    #tableData{
        margin: 20px 0;
    }
    #tableData td{
        text-align: center;
        max-width: 100px;
        min-width: 100px;
    }
    #tableData th{
        text-align: center;
        max-width: 100px;
        min-width: 100px;
    }
    .tableCon{
        width: 100%;
        overflow-x: auto;
    }
</style>
<body>
<div id="index">
    <div class="layui-container" style="width: 100%;">
        <div class="layui-row" style="margin-top: 10px;">
            <div class="layui-col-md2 ">
                <select class="selectpicker" id="platformId"  title="请选择平台名称"   style="width:100%;" >

                </select>
            </div>
            <div class="layui-col-md1 " style="padding-left: 20px;width: 140px;">
                <div class="btn-group" role="group" id="timetype">
                    <div class="btn btn-default active" id="timetype1" data-id="1">日</div>
                    <div class="btn btn-default" id="timetype2" data-id="2">周</div>
                    <div class="btn btn-default" id="timetype3" data-id="3">月</div>
                </div>
            </div>
            <div class="layui-col-md2" style="padding-left: 20px;">
                <input type="text" class="form-control" required  id="TimeDate"  placeholder="请输入查询日期"  autocomplete="off" >
                <input type="text" class="form-control" required style="display: none"  id="TimeYear"  placeholder="请选择年份"  autocomplete="off" >
                <input type="text" class="form-control" required style="display: none" id="TimeMonth"  placeholder="请输入查询月份"  autocomplete="off" >
            </div>
            <div class="layui-col-md1 weeks" style="padding-left: 20px;" >
                <select class="selectpicker"   data-live-search="true"  id="weeks" title="请选择周"   style="width:100%">

                </select>
            </div>
            <div class="layui-col-md2" style="padding-left: 20px;">
                <select class="selectpicker"  id="siteSelect" data-actions-box="true" data-select-all-text="全选" data-deselect-all-text="取消全选" multiple title="请选择字段"  style="width:100%;"  data-live-search="true"></select>
            </div>
            <div class="layui-col-md3 " style="padding-left: 20px;">
                <div class="btn btn-default" id="search" onclick="reload()">查询</div>
                <div class="btn btn-default" id="同步" onclick="transSame()">同步</div>
                <#if shiro.hasPermission("data:dataQuery:export")>
                <div class="btn btn-default" id="export">导出</div>
            </#if>
        </div>
    </div>
</div>
<div class="col-sm-12 select-info table-striped">
    <!--<table id="bootstrap-table" data-mobile-responsive="true"></table>-->
    <div class="tableCon">
        <table class="table table-bordered table-hover" id="tableData" >
            <!--<tr>-->
            <!--<th>类型[item]</th>-->
            <!--<th>有银子</th>-->
            <!--<th>趣转发</th>-->
            <!--</tr>-->
            <!--<tr>-->
            <!--<td>转发人数[param]</td>-->
            <!--<td>1[value]</td>-->
            <!--<td>2</td>-->
            <!--</tr>-->
            <!--<tr>-->
            <!--<td>转发人数[param]</td>-->
            <!--<td>1[value]</td>-->
            <!--<td>2</td>-->
            <!--</tr>-->
        </table>
    </div>
    <!--<table class="table table-bordered table-hover">-->
    <!--<tr>-->
    <!--<th>类型</th>-->
    <!--<th>有银子</th>-->
    <!--<th>趣转发</th>-->
    <!--</tr>-->
    <!--<tr>-->
    <!--<td>-->
    <!--转发人数-->
    <!--</td>-->
    <!--<td>-->
    <!--<div>-->
    <!--<span>对比前</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>对比后</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>上升幅度</span>-->
    <!--<span>1%</span>-->
    <!--</div>-->
    <!--</td>-->
    <!--<td>-->
    <!--<div>-->
    <!--<span>对比前</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>对比后</span>-->
    <!--<span>1</span>-->
    <!--</div>-->
    <!--<div>-->
    <!--<span>上升幅度</span>-->
    <!--<span>1%</span>-->
    <!--</div>-->
    <!--</td>-->
    <!--</tr>-->

    <!--</table>-->
</div>

<script>
    var laydate = layui.laydate;
    function gettime(num){
        var _thisdate =new Date() - (1000*60 *60 *24*num)
        var date = new Date(_thisdate);
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
    //初始化默认时间
    var startTimes ='';
    var endTimes='';
    var now = new Date();
    var year = now.getFullYear();
    var timeIndex = 0;
  $(function () {
      laydate.render({
          elem: '#TimeDate',
          range: true,
          position: 'fixed',
          change:function(value, date, endDate){

          }
      });
      laydate.render({
          elem: '#TimeYear',
          type: 'year',
          value: new Date(),
          position: 'fixed',
          done:function(value, date, endDate){
              getWeek(value)
          }
      });
      laydate.render({
          elem: '#TimeMonth',
          type: 'month',
          value: new Date(),
          position: 'fixed',
          done:function(value, date, endDate){
              console.log(value, date, endDate,'3333333333333')
          }
      });
      $('#TimeDate').val(gettime(30)+' - '+gettime(1));
      startTimes = gettime(30);
      endTimes = gettime(1);
      getWeek(year);
      $('.weeks').hide();
      initFn();
  });
    $('#timetype .btn').each(function(index){
        $(this).click(function(){
            $('.form-control').hide()
            $('.weeks').hide()
            timeIndex = index;
            if(index==0){
                $('#TimeDate').show();
            }else if(index==1){
                $('.weeks').show()
                $('#TimeYear').show();
            }else if(index==2){
                $('#TimeMonth').show();
            }
            $('#timetype .btn').removeClass('active');
            $(this).addClass('active');
            reload()
        })
    });
    $('#export').click(function(){
        // var data={
        //     "startDate":startTimes,
        //     "endDate":endTimes,
        //     "params":$('#siteSelect').val(),
        //     "platformId":$('#platformId').val()?$('#platformId').val():null
        // }
        var data = setParams();
        //console.log(baseURL +"platformStatis/downloadPlatformContrast?startDate="+data.startDate+"&endDate="+data.endDate+"&params="+data.params+"&platformId="+data.platformId)
        window.location.href=baseURL +"platformStatisExport/downloadPlatformProfitReportContrast?startDate="+data.startDate+"&endDate="+data.endDate+"&params="+data.params+"&platformId="+data.platformId

    })
    function setParams() {
        if(timeIndex==0){
            if(!$('#TimeDate').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#TimeDate').val().split(' - ')[0]?$('#TimeDate').val().split(' - ')[0]:'';
            endTimes = $('#TimeDate').val().split(' - ')[1]?$('#TimeDate').val().split(' - ')[1]:'';
        }else if(timeIndex==1){
            if(!$('#TimeYear').val() || !$('#weeks').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#weeks').val().split(' - ')[0]?$('#weeks').val().split(' - ')[0]:'';
            endTimes = $('#weeks').val().split(' - ')[1]?$('#weeks').val().split(' - ')[1]:'';
        }else if(timeIndex==2){
            if(!$('#TimeMonth').val()){
                layer.msg('时间格式不对')
                return;
            }
            startTimes = $('#TimeMonth').val() + '-01';
            endTimes =$('#TimeMonth').val()+'-'+new Date($('#TimeMonth').val().split('-')[0],$('#TimeMonth').val().split('-')[1],0).getDate()
        }
        // console.log(startTimes,endTimes,'sssssssssssss')

        // indexloading = layer.load(2);
        var params = {
            startDate:startTimes,
            endDate:endTimes,
            params:$('#siteSelect').val(),
            platformId:$('#platformId').val()?$('#platformId').val():null
        };
        var minData;
        var maxData;
        if(params.startDate>params.endDate){
            maxData = params.startDate;
            minData = params.endDate;
            params.endDate = maxData;
            params.startDate = minData;
        }
        return params;
    }
    function reload() {
        var params = setParams();
        $("#search").attr("disabled",'disabled');
        var  indexLoading = layer.load(2);
        $.ajax({
            type : "POST",
            url : baseURL + 'platformProfitReportStatics/findPlatformProfitReportStatics',
            contentType : "application/json",
            data : JSON.stringify(params),
            dataType:'json',
            success : function(r) {
                $("#search").attr("disabled",false);
                if (r.code === 0) {
                    showTable(r.result);
                    layer.close(indexLoading);
                } else {
                    alert(r.msg);
                }
            }
        });
    }
    function showTable(data) {
        var theadHtml = '<thead><tr><th>日期</th>';
        var tbodyHtml = '<tbody>';
        var thTitle = [];
        for(var i=0;i<data.statisData[0].length;i++){
            if(thTitle.indexOf(data.statisData[0][i].param)==-1){
                //thTitle.push(data.statisData[0][i].param);
                theadHtml = theadHtml + '<th><span data-toggle="tooltip" data-placement="top" title="'+data.statisData[0][i].paramDesc+'">' +data.statisData[0][i].param+'</span></th>';
            }
        }
        // for(var j=thTitle.length-1;j>-1;j--){
        for(var j=0;j<thTitle.length;j++){
           // theadHtml = theadHtml + '<th>' +thTitle[j]+'</th>';
            //<span data-toggle="tooltip" data-placement="top" title="'+data[0].statisData[0][j].paramDesc+'">'+thTitle[j]+'</span>
        }
        theadHtml = theadHtml + '</thead>';
        for(var h=0;h<data.statisData.length;h++){
            tbodyHtml = tbodyHtml + '<tr><td>'+data.statisDate[h]+'</td>';
            // for(var k=data.statisData[h].length-1;k>-1;k--){
            for(var k=0;k<data.statisData[h].length;k++){
                // if(data.statisData[h][k].riseOrFall ==1){
                //     tbodyHtml = tbodyHtml + '<td>' + data.statisData[h][k].value + '<span style="padding-left: 10px;"></span>'+ data.statisData[h][k].rateValue + '<span class="glyphicon glyphicon-arrow-up"></span></td>';
                // }else{
                //     tbodyHtml = tbodyHtml + '<td>' + data.statisData[h][k].value + '<span style="padding-left: 10px;"></span>'+ data.statisData[h][k].rateValue + '<span class="glyphicon glyphicon-arrow-down"></span></td>';
                // }
                tbodyHtml = tbodyHtml + '<td>' + data.statisData[h][k].value + '<span style="padding-left: 10px;"></span></td>';
            }
        }
        tbodyHtml = tbodyHtml + '</tbody>';
        var str = theadHtml + tbodyHtml;
        $("#tableData").html(str);
        $('[data-toggle="tooltip"]').tooltip();
    }
    function getWeek(years) {
        function formatDig(num) {
            return num > 9 ? '' + num : '0' + num;
        }
        function add0(m) {
            return m < 10 ? '0' + m : m
        }
        function formatDate(mill) {
            var time = new Date(mill);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            return y + '-' + add0(m) + '-' + add0(d);
        }
        function* createWeeks(year) {
            const ONE_DAY = 24 * 3600 * 1000;
            let start = new Date(year, 0, 1),
                end = new Date(year, 11, 31);
            let firstDay = start.getDay() || 7,
                lastDay = end.getDay() || 7;
            let startTime = +start,
                endTime = startTime + (7 - firstDay) * ONE_DAY,
                _endTime = end - (7 - lastDay) * ONE_DAY;
            yield [startTime, endTime];
            startTime = endTime + ONE_DAY;
            endTime = endTime + 7 * ONE_DAY;
            while (endTime < _endTime) {
                yield [startTime, endTime];
                startTime = endTime + ONE_DAY;
                endTime = endTime + 7 * ONE_DAY;
            }
            yield [startTime, +end];
        }
        let index = 1;
        var obj = {}
        var _html ="";
        var _index ='';
        for (let i of createWeeks(years)) {
            let start = i[0],
                end = i[1];
            if(formatDig(getWeekOfYear())==formatDig(index)){
                _index =formatDate(start)+' - '+formatDate(end);
            }
            _html = _html + '<option value="'+formatDate(start)+' - '+formatDate(end)+'">第' + (formatDig(index++)) + '周</option>'

        }
        $('#weeks').html(_html);
        $('#weeks').selectpicker('val',_index?_index:'');
        $('#weeks').selectpicker('refresh');
    }
    function transIntData(arr) {
        // console.log(arr);
        var newArr = [];
        arr.map(function (item) {
            newArr.push(parseInt(item));
        });
        return newArr;
    }
    function getWeekOfYear(){
        var today = new Date();
        var firstDay = new Date(today.getFullYear(),0, 1);
        var dayOfWeek = firstDay.getDay();
        var spendDay= 1;
        if (dayOfWeek !=0) {
            spendDay=7-dayOfWeek+1;
        }
        firstDay = new Date(today.getFullYear(),0, 1+spendDay);
        var d =Math.ceil((today.valueOf()- firstDay.valueOf())/ 86400000);
        var result =Math.ceil(d/7);
        return result+1;
    };
    function initFn(){
        $.ajax({
            type : "get",
            url : baseURL+"platform/findAllPlatformOrderByOnlineTime",
            dataType : "json",
            success: function(data) {
                if(data.code==0){
                    var _html = ''
                    for(var i=0;i<data.platformList.length;i++){
                        if(data.platformList[i].onlineTime){
                            _html = _html + '<option value="'+data.platformList[i].platformId+'">'+data.platformList[i].nickName+'  ('+data.platformList[i].onlineTime+')</option>'
                        }else{
                            _html = _html + '<option value="'+data.platformList[i].platformId+'">'+data.platformList[i].nickName+'</option>';
                        }
                    }
                    $('#platformId').append(_html);
                    $('#platformId').val(data.platformList[0].platformId);
                    $('#platformId').selectpicker('refresh');

                    $.ajax({
                        type : "post",
                        url : baseURL+"platformStatis/getPlatformProfitReportQueryParam",
                        data:JSON.stringify({
                            'paramType':0
                        }),
                        contentType : "application/json",
                        dataType : "json",
                        success: function(data) {
                            if(data.code==0){
                                var _html = '';
                                var dataVal = [];
                                for(var i=0;i<data.result.length;i++){
                                    _html = _html + '<option value="'+data.result[i].dateKey+'">'+data.result[i].dataName+'</option>';
                                    dataVal.push(data.result[i].dateKey);
                                }
                                $('#siteSelect').append(_html);
                                $('#siteSelect').val(dataVal);
                                $('#siteSelect').selectpicker('refresh');
                                setTimeout(function () {
                                    var params = {
                                        startDate:startTimes,
                                        endDate:endTimes,
                                        params:$('#siteSelect').val(),
                                        platformId:$('#platformId').val()?$('#platformId').val():null
                                    };
                                    var  indexLoading = layer.load(2);
                                    $.ajax({
                                        type : "POST",
                                        url : baseURL + 'platformProfitReportStatics/findPlatformProfitReportStatics',
                                        contentType : "application/json",
                                        data : JSON.stringify(params),
                                        dataType:'json',
                                        success : function(r) {
                                            if (r.code === 0) {
                                                showTable(r.result);
                                                layer.close(indexLoading);
                                            } else {
                                                alert(r.msg);
                                            }
                                        }
                                    });
                                },500);

                            }else{
                                layer.msg('数据获取失败');
                            }
                        },
                        error:function(){

                            layer.msg('数据获取失败');
                        }
                    });
                }else{
                    layer.msg('数据获取失败');
                }
            },
            error:function(){

                layer.msg('数据获取失败');
            }
        });
    }
function transSame() {
    layer.open({
        type: 1,
        skin: 'layui-layer-molv',
        title: "同步盈亏数据",
        area: ['550px', '450px'],
        shadeClose: false,
        content:modalCon(),
        btn: ['确定', '取消'],
        success:function (layero, index) {
            //console.log(index,'111111');
            layDateConfig();
        },
        btn1: function (index) {
            if($('#modalDate').val()){
                var  startTimes = $('#modalDate').val().split(' - ')[0]?$('#modalDate').val().split(' - ')[0]:'';
                var  endTimes = $('#modalDate').val().split(' - ')[1]?$('#modalDate').val().split(' - ')[1]:'';
                var  startDate = null;
                var  endDate = null;
                if(startTimes > endTimes){
                    startDate = endTimes;
                    endDate = startTimes;
                }else{
                    startDate = startTimes;
                    endDate = endTimes;
                }
                var params = {
                    platformId:$('#platformId').val()?$('#platformId').val():null,
                    startDate:startDate,
                    endDate:endDate
                };
                $.ajax({
                    type: "POST",
                    url: baseURL + "platformProfitReportStatics/syncPlatformProfitReportStaticsByTimeTask",
                    contentType : "application/json",
                    data:JSON.stringify(params),
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 0) {
                            layer.close(index);
                                alert('操作成功', function() {

                            });
                        } else {
                            layer.alert(result.msg);
                        }
                    }
                });
            }else{
                layer.alert('请选择时间范围!');
            }

        }
    });
}
function modalCon() {
        return  ' <div class="row" style="width:98%;margin: 20px auto">'
            +'<div class="col-sm-12">'
            +'<div class="input-group">'
            +'<span class="input-group-addon"> 选择时间范围:</span>'
            + '<input type="text" class="form-control" required  id="modalDate"  style="width:100%;"  placeholder="请输入查询日期"  autocomplete="off" >'
            +'</div>'
            +'</div>'
            +'</div>';
}
function layDateConfig() {
    var laydate = layui.laydate;
    laydate.render({
        elem: '#modalDate',
        range: true,
        position: 'fixed',
        change:function(value, date, endDate){

        }
    });
    $('#modalDate').val(gettime(1)+' - '+gettime(1));
}
</script>

</body>

</html>